from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                              QRadioButton, QSpinBox, QPushButton, QGroupBox,
                              QGridLayout, QButtonGroup, QFrame, QComboBox)
from PySide6.QtCore import Qt, Signal, QTimer
from PySide6.QtGui import QFont, QCursor, QPainter, QPen, QColor
import pyautogui

class SmartDetectionDialog(QDialog):
    """智能检测区域设置对话框 - 自动避开准星"""
    
    def __init__(self, trigger_item, parent=None):
        super().__init__(parent)
        self.trigger_item = trigger_item
        self.setWindowTitle("智能检测区域设置")
        self.setFixedSize(600, 500)
        self.setup_ui()
        self.load_settings()
        
    def setup_ui(self):
        layout = QVBoxLayout(self)
        
        # 标题
        title_label = QLabel("智能检测区域设置")
        title_font = QFont()
        title_font.setPointSize(14)
        title_font.setBold(True)
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(title_label)
        
        # 说明文字
        info_label = QLabel("自动在屏幕中心周围设置检测区域，智能避开游戏准星等中心元素")
        info_label.setStyleSheet("color: gray; margin: 10px;")
        info_label.setWordWrap(True)
        layout.addWidget(info_label)
        
        # 检测模式选择
        mode_group = QGroupBox("检测模式")
        mode_layout = QVBoxLayout(mode_group)
        
        self.mode_group = QButtonGroup()
        
        # 智能中心周围检测
        self.smart_radio = QRadioButton("智能中心周围检测（推荐）")
        self.smart_radio.setToolTip("在屏幕中心周围自动设置检测区域，避开准星")
        mode_layout.addWidget(self.smart_radio)
        self.mode_group.addButton(self.smart_radio, 0)
        
        # 传统中心检测
        self.center_radio = QRadioButton("屏幕中心检测")
        self.center_radio.setToolTip("直接检测屏幕正中心（可能检测到准星）")
        mode_layout.addWidget(self.center_radio)
        self.mode_group.addButton(self.center_radio, 1)
        
        layout.addWidget(mode_group)
        
        # 智能检测设置
        smart_group = QGroupBox("智能检测参数")
        smart_layout = QGridLayout(smart_group)
        
        # 检测位置选择
        smart_layout.addWidget(QLabel("检测位置:"), 0, 0)
        self.position_combo = QComboBox()
        self.position_combo.addItems([
            "右上角 (推荐)",
            "左上角", 
            "右下角",
            "左下角",
            "自动选择最佳位置"
        ])
        self.position_combo.setCurrentIndex(0)
        smart_layout.addWidget(self.position_combo, 0, 1)
        
        # 偏移距离
        smart_layout.addWidget(QLabel("偏移距离:"), 1, 0)
        self.offset_spin = QSpinBox()
        self.offset_spin.setRange(10, 100)
        self.offset_spin.setValue(30)
        self.offset_spin.setSuffix(" 像素")
        self.offset_spin.setToolTip("距离屏幕中心的偏移距离")
        smart_layout.addWidget(self.offset_spin, 1, 1)
        
        # 检测区域大小
        smart_layout.addWidget(QLabel("区域宽度:"), 2, 0)
        self.width_spin = QSpinBox()
        self.width_spin.setRange(5, 50)
        self.width_spin.setValue(20)
        self.width_spin.setSuffix(" 像素")
        smart_layout.addWidget(self.width_spin, 2, 1)
        
        smart_layout.addWidget(QLabel("区域高度:"), 3, 0)
        self.height_spin = QSpinBox()
        self.height_spin.setRange(5, 50)
        self.height_spin.setValue(20)
        self.height_spin.setSuffix(" 像素")
        smart_layout.addWidget(self.height_spin, 3, 1)
        
        layout.addWidget(smart_group)
        
        # 预设配置
        preset_group = QGroupBox("预设配置")
        preset_layout = QHBoxLayout(preset_group)
        
        self.fps_preset_btn = QPushButton("FPS游戏预设")
        self.fps_preset_btn.clicked.connect(self.apply_fps_preset)
        self.fps_preset_btn.setToolTip("适用于FPS游戏的检测设置")
        preset_layout.addWidget(self.fps_preset_btn)
        
        self.strategy_preset_btn = QPushButton("策略游戏预设")
        self.strategy_preset_btn.clicked.connect(self.apply_strategy_preset)
        self.strategy_preset_btn.setToolTip("适用于策略游戏的检测设置")
        preset_layout.addWidget(self.strategy_preset_btn)
        
        self.mobile_preset_btn = QPushButton("手游模拟器预设")
        self.mobile_preset_btn.clicked.connect(self.apply_mobile_preset)
        self.mobile_preset_btn.setToolTip("适用于手游模拟器的检测设置")
        preset_layout.addWidget(self.mobile_preset_btn)
        
        layout.addWidget(preset_group)
        
        # 实时预览
        preview_group = QGroupBox("实时预览")
        preview_layout = QVBoxLayout(preview_group)
        
        self.preview_label = QLabel("检测区域: 未设置")
        preview_layout.addWidget(self.preview_label)
        
        self.preview_btn = QPushButton("开始实时预览")
        self.preview_btn.clicked.connect(self.toggle_preview)
        preview_layout.addWidget(self.preview_btn)
        
        # 预览说明
        preview_info = QLabel("预览将显示检测区域的位置和当前颜色值")
        preview_info.setStyleSheet("color: gray; font-size: 10px;")
        preview_layout.addWidget(preview_info)
        
        layout.addWidget(preview_group)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        
        self.ok_btn = QPushButton("确定")
        self.ok_btn.clicked.connect(self.accept)
        button_layout.addWidget(self.ok_btn)
        
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_btn)
        
        layout.addLayout(button_layout)
        
        # 连接信号
        self.mode_group.buttonClicked.connect(self.on_mode_changed)
        self.smart_radio.toggled.connect(smart_group.setEnabled)
        self.smart_radio.toggled.connect(preset_group.setEnabled)
        
        # 预览定时器
        self.preview_timer = QTimer()
        self.preview_timer.timeout.connect(self.update_preview)
        self.is_previewing = False
        
        # 默认选择智能模式
        self.smart_radio.setChecked(True)
        
    def load_settings(self):
        """加载当前设置"""
        # 设置检测模式
        if getattr(self.trigger_item, 'detection_mode', 'smart_around_center') == "smart_around_center":
            self.smart_radio.setChecked(True)
        else:
            self.center_radio.setChecked(True)
            
        # 设置智能检测参数
        self.offset_spin.setValue(getattr(self.trigger_item, 'detection_offset_x', 30))
        self.width_spin.setValue(getattr(self.trigger_item, 'detection_area_width', 20))
        self.height_spin.setValue(getattr(self.trigger_item, 'detection_area_height', 20))
        
        # 设置检测位置
        position = getattr(self.trigger_item, 'detection_position', 'top_right')
        position_map = {
            'top_right': 0,
            'top_left': 1,
            'bottom_right': 2,
            'bottom_left': 3,
            'auto': 4
        }
        self.position_combo.setCurrentIndex(position_map.get(position, 0))
        
        # 更新UI状态
        self.on_mode_changed()
        
    def on_mode_changed(self):
        """检测模式改变时的处理"""
        is_smart = self.smart_radio.isChecked()
        # 智能模式相关控件的启用状态已通过信号连接处理
        
    def apply_fps_preset(self):
        """应用FPS游戏预设"""
        self.position_combo.setCurrentIndex(0)  # 右上角
        self.offset_spin.setValue(35)  # 较大偏移避开准星
        self.width_spin.setValue(15)   # 较小区域提高精度
        self.height_spin.setValue(15)
        print("已应用FPS游戏预设")
        
    def apply_strategy_preset(self):
        """应用策略游戏预设"""
        self.position_combo.setCurrentIndex(4)  # 自动选择
        self.offset_spin.setValue(25)  # 中等偏移
        self.width_spin.setValue(25)   # 中等区域
        self.height_spin.setValue(25)
        print("已应用策略游戏预设")
        
    def apply_mobile_preset(self):
        """应用手游模拟器预设"""
        self.position_combo.setCurrentIndex(0)  # 右上角
        self.offset_spin.setValue(40)  # 较大偏移适应UI
        self.width_spin.setValue(30)   # 较大区域适应分辨率
        self.height_spin.setValue(30)
        print("已应用手游模拟器预设")
        
    def toggle_preview(self):
        """切换实时预览"""
        if self.is_previewing:
            self.stop_preview()
        else:
            self.start_preview()
            
    def start_preview(self):
        """开始实时预览"""
        self.is_previewing = True
        self.preview_btn.setText("停止预览")
        self.preview_timer.start(500)  # 每500ms更新一次
        print("开始实时预览智能检测区域")
        
    def stop_preview(self):
        """停止实时预览"""
        self.is_previewing = False
        self.preview_btn.setText("开始实时预览")
        self.preview_timer.stop()
        self.preview_label.setText("检测区域: 预览已停止")
        print("停止实时预览")
        
    def update_preview(self):
        """更新预览信息"""
        try:
            if self.smart_radio.isChecked():
                # 计算智能检测区域
                left, top, right, bottom = self.calculate_smart_detection_area()
                center_x = (left + right) // 2
                center_y = (top + bottom) // 2
                
                # 获取该区域的平均颜色
                from PIL import ImageGrab
                screenshot = ImageGrab.grab()
                colors = []
                
                for x in range(left, right + 1):
                    for y in range(top, bottom + 1):
                        if 0 <= x < screenshot.width and 0 <= y < screenshot.height:
                            colors.append(screenshot.getpixel((x, y)))
                
                if colors:
                    avg_r = sum(c[0] for c in colors) // len(colors)
                    avg_g = sum(c[1] for c in colors) // len(colors)
                    avg_b = sum(c[2] for c in colors) // len(colors)
                    
                    self.preview_label.setText(
                        f"智能检测区域: ({left},{top}) 到 ({right},{bottom}) | "
                        f"中心: ({center_x},{center_y}) | "
                        f"颜色: RGB({avg_r},{avg_g},{avg_b}) | "
                        f"#{avg_r:02x}{avg_g:02x}{avg_b:02x}"
                    )
                else:
                    self.preview_label.setText("检测区域: 无效区域")
            else:
                # 屏幕中心模式
                screen_width, screen_height = pyautogui.size()
                center_x, center_y = screen_width // 2, screen_height // 2
                
                from PIL import ImageGrab
                screenshot = ImageGrab.grab()
                color = screenshot.getpixel((center_x, center_y))
                
                self.preview_label.setText(
                    f"屏幕中心: ({center_x},{center_y}) | "
                    f"颜色: RGB({color[0]},{color[1]},{color[2]}) | "
                    f"#{color[0]:02x}{color[1]:02x}{color[2]:02x}"
                )
                
        except Exception as e:
            self.preview_label.setText(f"预览错误: {e}")
            
    def calculate_smart_detection_area(self):
        """计算智能检测区域的坐标"""
        screen_width, screen_height = pyautogui.size()
        center_x, center_y = screen_width // 2, screen_height // 2
        
        offset = self.offset_spin.value()
        width = self.width_spin.value()
        height = self.height_spin.value()
        
        position_index = self.position_combo.currentIndex()
        
        if position_index == 0:  # 右上角
            left = center_x + offset
            top = center_y - offset - height
        elif position_index == 1:  # 左上角
            left = center_x - offset - width
            top = center_y - offset - height
        elif position_index == 2:  # 右下角
            left = center_x + offset
            top = center_y + offset
        elif position_index == 3:  # 左下角
            left = center_x - offset - width
            top = center_y + offset
        else:  # 自动选择 - 默认右上角
            left = center_x + offset
            top = center_y - offset - height
            
        right = left + width
        bottom = top + height
        
        return left, top, right, bottom
        
    def get_settings(self):
        """获取设置结果"""
        settings = {}
        
        if self.smart_radio.isChecked():
            settings['detection_mode'] = "smart_around_center"
        else:
            settings['detection_mode'] = "center"
            
        settings['detection_offset_x'] = self.offset_spin.value()
        settings['detection_offset_y'] = self.offset_spin.value()  # 使用相同偏移
        settings['detection_area_width'] = self.width_spin.value()
        settings['detection_area_height'] = self.height_spin.value()
        
        position_map = ['top_right', 'top_left', 'bottom_right', 'bottom_left', 'auto']
        settings['detection_position'] = position_map[self.position_combo.currentIndex()]
        
        return settings
        
    def accept(self):
        """确定按钮处理"""
        self.stop_preview()
        
        # 应用设置
        settings = self.get_settings()
        self.trigger_item.detection_mode = settings['detection_mode']
        self.trigger_item.detection_offset_x = settings['detection_offset_x']
        self.trigger_item.detection_offset_y = settings['detection_offset_y']
        self.trigger_item.detection_area_width = settings['detection_area_width']
        self.trigger_item.detection_area_height = settings['detection_area_height']
        self.trigger_item.detection_position = settings['detection_position']
        
        print(f"智能检测区域设置已保存: {settings}")
        super().accept()
        
    def reject(self):
        """取消按钮处理"""
        self.stop_preview()
        super().reject()
        
    def closeEvent(self, event):
        """窗口关闭时清理"""
        self.stop_preview()
        super().closeEvent(event)
